using System;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace TypedMvcActionHelper
{
    public static class TypedUrlGenerator
    {
        /// <summary>
        /// Generate url like http://localhost/****/User/Search
        /// </summary>
        /// <typeparam name="TController"></typeparam>
        /// <param name="urlHelper"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static string Url<TController>(this UrlHelper urlHelper,Expression<Func<TController, ActionResult>> expression)
             where TController : ControllerBase
        {
            var rootUrl = GetRootUrl(urlHelper);

            var url = rootUrl+urlHelper.GetRightUrlPart<TController>(expression);

            return url;
        }

        /// <summary>
        /// Generate url like User/Search
        /// </summary>
        /// <typeparam name="TController"></typeparam>
        /// <param name="urlHelper"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, ActionResult>> expression)
             where TController : ControllerBase
        {

            var url = urlHelper.GetRightUrlPart(expression);

            return url;
        }


        private static string GetRightUrlPart<TController>(this UrlHelper urlHelper,Expression<Func<TController, ActionResult>> expression)
            where TController:ControllerBase
        {
            var expressionExtractor=MvcActionExpressionExtractor.For<TController>();

            var controllerName = expressionExtractor.GetControllerName();
            var actionName = expressionExtractor.GetActionName(expression);
            var routeValueDictionary = expressionExtractor.GetRouteValueDictionary(expression);

            var url = urlHelper.Action(actionName, controllerName, routeValueDictionary);

            return url;
        }


        private static string GetRootUrl(UrlHelper url)
        {
            var requestUrl = @url.RequestContext.HttpContext.Request.Url;
            var rootUrl = requestUrl.Scheme + "://" + requestUrl.Authority;

            return rootUrl;
        }     
    }
}